import 'dart:io';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/utils/mesh_url.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

import '../../function/states/activity_state.dart';
import '../../function/states/user_state.dart';
import '../../function/models/activity_model.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/widgets/login_dialog.dart';
import '../../function/routes/app_route_manager.dart';

/// 上传分享图片页面
class UploadSharePage extends StatefulWidget {
  final String? defaultActivityId; // 默认选中的活动ID

  const UploadSharePage({super.key, this.defaultActivityId});

  @override
  State<UploadSharePage> createState() => _UploadSharePageState();
}

class _UploadSharePageState extends State<UploadSharePage> {
  String? _selectedImagePath; // 选中的图片路径
  String? _selectedActivityId; // 选中的活动ID
  List<ActivityModel> _activityList = []; // 活动列表

  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  /// 初始化数据
  void _initializeData() {
    // 获取所有活动
    _activityList = ActivityState.getAllActivities();

    // 设置默认选中的活动
    if (widget.defaultActivityId != null) {
      _selectedActivityId = widget.defaultActivityId;
    } else if (_activityList.isNotEmpty) {
      _selectedActivityId = _activityList.first.activityId;
    }
  }

  /// 获取动物名字
  String _getAnimalName(String activityTitle) {
    if (activityTitle.contains('lemurs')) {
      return 'Lemur';
    } else if (activityTitle.contains('Radiant Turtle')) {
      return 'Radiation Turtle';
    }
    return activityTitle; // 如果无法识别，返回原标题
  }

  /// 构建活动选择按钮
  Widget _buildActivityButton(ActivityModel activity) {
    final isSelected = _selectedActivityId == activity.activityId;

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedActivityId = activity.activityId;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 6.h, horizontal: 16.w),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFF663507) : Colors.transparent,
          borderRadius: BorderRadius.circular(15.r),
          border: Border.all(
            color:
                isSelected
                    ? const Color(0xFFFF8A3C)
                    : Colors.white.withOpacity(0.3),
            width: isSelected ? 1.w : 1.w,
          ),
        ),
        child:
            Text(_getAnimalName(activity.title))
                .fontSize(14.sp)
                .textColor(Colors.white)
                .fontWeight(FontWeight.w600) // 选中状态字体更粗
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
                )
                .center(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              // 可滚动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    children: [
                      SizedBox(height: 20.h),

                      // 图片上传区域
                      _buildImageUploadSection(),

                      SizedBox(height: 30.h),

                      // 活动选择区域
                      _buildActivitySelectionSection(),

                      SizedBox(height: 40.h),

                      // 发布按钮
                      _buildReleaseButton(),

                      SizedBox(height: 20.h),

                      // EULA链接
                      _buildEulaLink(),

                      SizedBox(height: 20.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          AnimatedTapWidget(
            onTap: () => AppRouteManager.goBack(),
            child: Icon(Icons.chevron_left, color: Colors.white, size: 24.w),
          ),

          SizedBox(width: 8.w),

          // 标题
          Text('Upload Image')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w600)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
              ),
        ],
      ),
    );
  }

  /// 构建图片上传区域
  Widget _buildImageUploadSection() {
    return Container(
      width: double.infinity,
      height: 206.h,
      decoration: BoxDecoration(
        color: const Color(0xFF663507).withOpacity(0.8),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.3), width: 1.w),
      ),
      child:
          _selectedImagePath != null
              ? _buildSelectedImage()
              : _buildImageUploadPlaceholder(),
    );
  }

  /// 构建图片上传占位符
  Widget _buildImageUploadPlaceholder() {
    return AnimatedTapWidget(
      onTap: _selectImage,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(16.r)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/image.png', width: 20.w, height: 20.w),
            SizedBox(width: 6.w),
            Text('Upload Image')
                .fontSize(16.sp)
                .textColor(Colors.white.withOpacity(0.6))
                .fontWeight(FontWeight.w600)
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
                ),
          ],
        ),
      ),
    );
  }

  /// 构建已选中的图片
  Widget _buildSelectedImage() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16.r),
        image: DecorationImage(
          image: FileImage(File(_selectedImagePath!)),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          // 重新选择按钮
          Positioned(
            top: 12.h,
            right: 12.w,
            child: AnimatedTapWidget(
              onTap: _selectImage,
              child: Container(
                padding: EdgeInsets.all(8.w),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Icon(Icons.edit, color: Colors.white, size: 16.w),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建活动选择区域
  Widget _buildActivitySelectionSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题
        Text('Select Activity')
            .fontSize(16.sp)
            .textColor(Colors.white)
            .fontWeight(FontWeight.w600)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
            )
            .paddingBottom(16.h),

        // 活动选择按钮
        Row(
          children: [
            // 第一个活动按钮
            _buildActivityButton(_activityList[0]),
            SizedBox(width: 12.w),
            // 第二个活动按钮
            _buildActivityButton(_activityList[1]),
          ],
        ),
      ],
    );
  }

  /// 构建发布按钮
  Widget _buildReleaseButton() {
    final canRelease =
        _selectedImagePath != null && _selectedActivityId != null;

    return AnimatedTapWidget(
      onTap: canRelease ? _handleRelease : null,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 46.w),
        decoration: BoxDecoration(
          color: const Color(0xFF854612),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child:
            Text('Release')
                .fontSize(16.sp)
                .textColor(Colors.white)
                .fontWeight(FontWeight.w600)
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
                )
                .center(),
      ).configBorderWidget(
        borderRadius: 16.r,
        borderColor: Colors.white.withOpacity(0.3),
        borderWidth: 1.w,
      ),
    );
  }

  /// 构建EULA链接
  Widget _buildEulaLink() {
    return GestureDetector(
      onTap: () {
        MeshUrl.launchEula();
      },
      child:
          Text(
            'EULA',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontWeight: FontWeight.w400,
              fontFamily:
                  GoogleFonts.quicksand(fontWeight: FontWeight.w400).fontFamily,
              decoration: TextDecoration.underline,
            ),
          ).center(),
    );
  }

  /// 选择图片
  Future<void> _selectImage() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        final file = await asset.file;

        if (file != null) {
          // 复制图片到本地目录
          final localPath = await _copyImageToLocal(file);
          setState(() {
            _selectedImagePath = localPath;
          });
        }
      }
    } catch (e) {
      ToastWidget.showError('Failed to select image: $e');
    }
  }

  /// 复制图片到本地目录
  Future<String> _copyImageToLocal(File sourceFile) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final imagesDir = Directory(path.join(directory.path, 'shared_images'));

      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg';
      final targetPath = path.join(imagesDir.path, fileName);
      final targetFile = await sourceFile.copy(targetPath);

      return targetFile.path;
    } catch (e) {
      throw Exception('Failed to copy image: $e');
    }
  }

  /// 处理发布
  void _handleRelease() {
    if (!UserState.checkLoginStatus()) {
      LoginDialog.show(context);
      return;
    }

    if (_selectedImagePath == null || _selectedActivityId == null) {
      ToastWidget.showWarning('Please select image and activity');
      return;
    }

    try {
      // 添加分享图片到状态管理
      ActivityState.shareToActivity(
        activityId: _selectedActivityId!,
        userId: UserState.getCurrentUserInfo()?.userId ?? 'unknown',
        imageUrl: _selectedImagePath!,
      );

      // 显示成功提示
      ToastWidget.showSuccess('Image shared successfully!');

      // 返回上一页
      AppRouteManager.goBack();
    } catch (e) {
      ToastWidget.showError('Failed to share image: $e');
    }
  }
}
